package org.xg.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName RefreshServlet
 * @date 2021/9/24 10:37
 **/
@WebServlet("/refresh")
public class RefreshServlet extends HttpServlet {
    private static final long serialVersionUID=1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object requestAttr = req.getAttribute("requestAttr");
        //获取存在上下文中的跳转时间
        int times = (int) getServletContext().getAttribute("time");
        //获取存在上下文中的错误信息
        String msg = (String) getServletContext().getAttribute("msg");
        /**
         *
         * 设置三个头信息，禁用浏览器缓存
         * Cache-Control : no-cache
         * Expires: -1 值是日期类型（setDateHeader()）
         *     Pragma : no-cache
         */
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        resp.setDateHeader("Expires", -1);
        //
        resp.setContentType("text/html;charset=UTF-8");
        //设置提示
        String title = msg + "，即将在" +
                times + "秒钟后跳转到登录页";
        //使用默认时区和语言环境获得一个日历
        Calendar cale = Calendar.getInstance();
        //将Calendar类型转换成Date类型
        Date tasktime = cale.getTime();
        //设置日期输出的格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //格式化输出
        String nowTime = df.format(tasktime);
        //只要倒计时时间没有到0，就直至输出下面内容
        if (times != 0) {
            resp.getWriter().write("<html>\n" +
                    "<head><title >" + title + "</title></head>\n" +
                    "<body bgcolor=\"#f0f0f0\">\n" +
                    "<h1 align=\"center\">编程帮  www.biancheng.net  提醒您：</h1>" +
                    "<h1 align=\"center\" style=\"font-family:arial;color:red;\">" + title + "</h1>\n" +
                    "<h1 align=\"center\">当前时间 是：" + nowTime + "</h1>\n" +
                    "<h1 align=\"center\">重定向通过request传递的数据为：" + requestAttr + "</h1>\n");
            //倒计时
            times--;
            //将倒计时的时间重新存入上下文中覆盖原来的值
            getServletContext().setAttribute("time", times);
            // 通过refresh头完成页面刷新
            resp.setHeader("refresh", "1;url=/ServletRed/refresh");
        } else {
            //倒计时归零，则跳转到登陆页面
            resp.sendRedirect("/ServletRed/index.html");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
